package wangjg.xuexiban.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;

public class ResoureUtil {

	public static Bitmap getImageResoure(String file) {
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			return loadImageResoure(fis);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("ResoureUtil", "getImageResoure", e);
		}finally{
			try{
				if(fis!=null)fis.close();
			}catch(Exception e){
				Log.e("ResoureUtil", "getImageResoure", e);
			}
		}
		return null;
	}
	
	public static Bitmap loadImageResoure(InputStream bis){
		Bitmap bitmap = null;
		
//		BitmapFactory.Options options = new BitmapFactory.Options();
//		options.inSampleSize = 8;// 图片的长宽都是原来的1/8
//		bitmap = BitmapFactory.decodeStream(bis, null, options);
		
		bitmap = BitmapFactory.decodeStream(bis);
		
		return bitmap;
	}
	
	public static void saveBitmap(Bitmap bitmap, String path){
		if(path==null||path.length()==0){
			return;
		}
		boolean png = false;
		if(path.toLowerCase().endsWith("png")){
			png = true;
		}
		File file = new File(path);
		FileOutputStream out=null;
		try {
			out = new FileOutputStream(file);
			if (bitmap.compress(png?Bitmap.CompressFormat.PNG:Bitmap.CompressFormat.JPEG, 70, out)) {
				out.flush();
				out.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try{
				if(out!=null)out.close();
			} catch (IOException e) {}
		}
	}
	

	// 缩放图片
	public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){
	   int srcWidth = bm.getWidth();
	   int srcHeight = bm.getHeight();
	   if(newWidth==srcWidth && newHeight==srcHeight){
		   return bm;
	   }
	   Matrix matrix = ResoureUtil.getZoomMatrix(srcWidth, srcHeight, newWidth, newHeight);
	   // 得到新的图片
	   Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, srcWidth, srcHeight, matrix, true);
	    return newbm;
	}
	
	public static Matrix getZoomMatrix(int srcWidth, int srcHeight, int newWidth ,int newHeight){
		   float scale ;
		   float srcWhScale = ((float)srcWidth / srcHeight);
		   float newWhScale = ((float)newWidth / newHeight);
		   if(srcWhScale>newWhScale){
			   scale = (float)newWidth/srcWidth;
		   }else{
			   scale = (float)newHeight/srcHeight;
		   }
		   Matrix matrix = new Matrix();
		   matrix.postScale(scale, scale);
		   
		   return matrix;
	}
}
